<?php


namespace App\Services\Tools;

use App\Exceptions\BasicException;
use App\Repositories\LogRepository;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class SmsCxyService
{
    private static $_error_msg = '';
    private static $_error_code = '';
    /**
     * @param $mobile
     * @param $type
     * @param array $param
     * @param int $limit
     * @param string $template_id
     * @return bool
     * @throws BasicException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public static function send($mobile, $type, $param = [], $limit = 1, $template_id = "")
    {
        $key = 'sms:' . $mobile . ':' . $type;
        if ($limit > 0 && app('redis')->get($key)) {
            throw new BasicException(0, $limit . '分钟可获取一次');
        }
        //短信发送
        $url = 'https://api.cxlnk.com/api/msgService/sendSms';
        $accessSecret = 'Mzk1NTk0NTIyMTY4MDM0MjQxNTE=';
        $accessKey = 'MTM2MDgxNTE=';
        $signCode = 'be2f6da6';
        $templateCode = 'e10bec4b';
        $msgType = 1;
        $sms_code = isset($param['code']) ? $param['code'] : self::getRandCode();

        $postData = [
            "accessKey" => $accessKey,
            "accessSecret" => $accessSecret,
            "signCode" => $signCode,
            "templateCode" => $templateCode,
            "mobile" => $mobile,
            "params" => [$sms_code],
            "msgType" => $msgType,
            "taskId" => "",
        ];

        if (!self::doCurl($postData, $url)) {
            throw new BasicException(0, '发送失败');
        }
//        if (env('SMS_REAL_SEND')) {
//        if (!self::doCurl($postData, $url)) {
//            throw new BasicException(0, '发送失败');
//        }
//        }

        app('model_sms_history')->create([
            'mobile' => $mobile,
            'code' => $sms_code,
            'add_time' => Carbon::now()->timestamp,
            'type' => $type
        ]);
        app('redis')->setex($key, $limit * 60, $sms_code);
        return true;
    }

    private static function getRandCode()
    {
        return mt_rand(1000, 9999);
    }

    protected static function doCurl($data, $url)
    {
        // 请求参数
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json;charset=utf-8', 'Accept: application/json'
        ));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
//        Log::info($output);
        if (!isset($output['code']) || $output['code'] != 200) {
            // 记录失败
            $logRtx = new LogRepository("cxy-sms-send");
            $logRtx->log("output", $output);
            $logRtx->File();
            return false;
        }
        return true;
//        return $verify_code == 0 ? true : false;
    }

    public static function verify($mobile, $code, $type)
    {
        $where = [
            'mobile' => $mobile,
            'type' => $type,
            'status' => 0,
        ];
        $data = app('model_sms_history')->where($where)->orderBy('id', 'desc')->first();
        $result = false;
        $key = 'u:login_error_times:' . $mobile . ':' . $type;

        if (isset($data) && $data->status == 0 && $data->code == $code) {
            if ($data->add_time < (Carbon::now()->timestamp - 1800)) {
                $status = 2;
                $result = false;
                self::$_error_msg = '验证码已过期';
            } else {
                $status = 1;
                $result = true;
            }
            app('model_sms_history')->where(['id' => $data->id, 'status' => 0])->update([
                'status' => $status,
                'update_time' => Carbon::now()->timestamp,
            ]);
        }
        //记录错误次数
        if (!$result) {
            self::$_error_msg = '验证码错误';
            $times = app('redis')->incr($key);
            if ($times >= 5) {
                app('model_sms_history')->where($where)->update([
                    'status' => 2,
                    'update_time' => Carbon::now()->timestamp,
                ]);
                self::$_error_msg = '验证码输入错误次数过多，已失效，请重新获取';
                app('redis')->del($key);

                return false;
            } elseif ($times == 1) {
                app('redis')->expire($key, strtotime(date('Ymd')) + 86400 - time());
            }
        }

        return $result;
    }
    public static function getErrorMsg(){
        return [
            'error_code' => self::$_error_code,
            'error_msg' => self::$_error_msg,
        ];
    }
}
